package com.fdb.efp.nls.service.impl.psd.credit;

import com.alibaba.fastjson.JSONObject;
import com.fdb.efp.edoc.service.facade.signature.PsdContResult;
import com.fdb.efp.nls.service.domain.NlsApplyInfo;
import com.fdb.efp.nls.service.domain.signature.SignatureRecord;
import com.fdb.efp.nls.service.domain.sx.NlsCreditInfo;
import com.fdb.efp.nls.service.facade.psd.PsdTmSignatureService;
import com.fdb.efp.nls.common.psd.PsdConstantSet;
import com.fdb.efp.nls.common.psd.PsdTmUtils;
import com.fdb.efp.nls.service.facade.SCfgParamService;
import com.fdb.efp.console.service.vo.SCfgParamVO;
import com.fdb.efp.nls.service.vo.CfcaSignInfoVO;
import com.fdb.efp.nls.service.vo.ImageBizDetailVO;
import com.fdb.efp.nls.service.vo.ImageBizInfoVO;
import com.fdb.efp.nls.service.facade.CfcaSignInfoService;
import com.fdb.efp.nls.service.facade.ImageBizDetailService;
import com.fdb.efp.nls.service.facade.ImageBizInfoService;
import com.fdb.efp.nls.service.facade.signature.PsdCertUploadService;
import com.fdb.efp.nls.service.facade.signature.PsdContService;
import com.fdb.efp.esb.common.constant.ElectronicSignatureEnums;
import com.fdb.efp.nls.service.dao.NlsApplyInfoDao;
import com.fdb.efp.nls.service.dao.signature.SignatureRecordDAO;
import com.fdb.efp.nls.service.dao.sx.NlsCreditInfoDao;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 普税贷授权书签章服务类--
 *
 * @author xiaojunhui<br />
 */
@Service("psdTmSignatureService")
public class PsdTmSignatureServiceImpl implements PsdTmSignatureService {

    private static Logger logger = LoggerFactory.getLogger(PsdTmSignatureServiceImpl.class);

    @Autowired
    private SignatureRecordDAO signatureRecordDAO;

    @Autowired
    private NlsCreditInfoDao nlsCreditInfoDao;

    @Autowired
    @Qualifier("cfcaSignInfoService")
    private CfcaSignInfoService cfcaSignInfoService;

    @Autowired
    private SCfgParamService sCfgParamService;

    @Autowired
    private PsdContService psdContService;

    @Autowired
    private PsdCertUploadService psdCertUploadService;

    @Autowired
    private NlsApplyInfoDao nlsApplyInfoDao;

    @Autowired
    private ImageBizDetailService imageBizDetailService;

    @Autowired
    private ImageBizInfoService imageBizInfoService;

    @Override
    public Boolean signature() {
        logger.info("开始进行在线签章");
        //获取配置的处理数量以及重试次数
        final int[] handleNumArr = getHandleNumArr();
        //获取待签订的数据
        final List<SignatureRecord> signatureRecords = signatureRecordDAO.getSignatureNlsListInTypes(PsdConstantSet.prdId, handleNumArr[1], StringUtils.join(PsdConstantSet.PSD_FILE_TM_TYPE_03, ",", PsdConstantSet.PSD_SX_CONT_TM_TYPE, ",", PsdConstantSet.PSD_YX_CONT_TM_TYPE), handleNumArr[0]);

        if (signatureRecords == null || signatureRecords.isEmpty()) {
            logger.info("在线签章：获取到需要处理的数据为空");
            return Boolean.TRUE;
        }
        logger.info("获取需要处理的脱敏的数据记录数为{}", signatureRecords.size());
        for (SignatureRecord signatureRecord : signatureRecords) {
            try {
                signatureRecord.setRetryNum(signatureRecord.getRetryNum() + 1);
                //判断状态 如果是02 那么需要走流程 如果是3 直接走下载
                if (signatureRecord.getSiuSta() == 1) {
                    continue;
                }
                NlsApplyInfo nlsApplyInfo = null;
                //用信申请记录
                if (PsdConstantSet.PSD_YX_CONT_TM_TYPE.equals(signatureRecord.getPolFileType())) {
                    NlsApplyInfo nlsApplyInfoPk = new NlsApplyInfo();
                    nlsApplyInfoPk.setApplySeq(signatureRecord.getApplySeq());
                    nlsApplyInfo = nlsApplyInfoDao.queryByPk(nlsApplyInfoPk);
                    if (Objects.isNull(nlsApplyInfo)) {
                        if (signatureRecord.getSiuSta() == 0) {
                            signatureRecord.setSiuSta(2);
                        }
                        signatureRecord.setLastUpdateTime(new Date());
                        signatureRecord.setErrMsg("查询用信信息为空");
                        signatureRecordDAO.updateByPrimaryKey(signatureRecord);
                        continue;
                    }
                }
                NlsCreditInfo pkParam = new NlsCreditInfo();
                pkParam.setLmtApplySeq(Objects.isNull(nlsApplyInfo) ? signatureRecord.getApplySeq() : nlsApplyInfo.getLmtApplySeq());
                final NlsCreditInfo nlsCreditInfo = nlsCreditInfoDao.queryByPk(pkParam);
                if (Objects.isNull(nlsCreditInfo)) {
                    if (signatureRecord.getSiuSta() == 0) {
                        signatureRecord.setSiuSta(2);
                    }
                    signatureRecord.setLastUpdateTime(new Date());
                    signatureRecord.setErrMsg("查询授信信息为空");
                    signatureRecordDAO.updateByPrimaryKey(signatureRecord);
                    continue;
                }
                String[] tempFileInfo = getTempFileInfo(signatureRecord);

                //判断状态 如果是3 直接走下载
                if (signatureRecord.getSiuSta() == 3) {
                    final PsdContResult psdContResult = psdContService.downSignFile(signatureRecord.getApplySeq(), signatureRecord.getSiuContNo(), tempFileInfo[3]);
                    if (psdContResult.isRetFlag()) {
                        signatureRecord.setSiuSta(1);
                        signatureRecord.setLastUpdateTime(new Date());
                        signatureRecord.setDwnRetMsg("下载文件成功");
                        signatureRecordDAO.updateByPrimaryKey(signatureRecord);
                        //插入上传表给定时器处理上传
                        psdCertUploadService.insert(psdContResult.getFileFullPath());
                        insertCfcaSignInfo(psdContResult, nlsCreditInfo, signatureRecord);
                        //插入明细表
                        insertImageBizDetail(signatureRecord.getApplySeq(), signatureRecord.getPolFileType(), FilenameUtils.getBaseName(psdContResult.getFileFullPath()), psdContResult.getFileFullPath());
                        insertImageBizInfo(signatureRecord, nlsCreditInfo);
                        continue;
                    } else {
                        signatureRecord.setSiuSta(3);
                        signatureRecord.setLastUpdateTime(new Date());
                        signatureRecord.setDwnRetMsg(psdContResult.getMsg());
                        signatureRecordDAO.updateByPrimaryKey(signatureRecord);
                        continue;
                    }
                }
                if (signatureRecord.getSiuSta() == 0 || signatureRecord.getSiuSta() == 2) {
                    //获取合同填充内容并且设置脱敏内容
                    Map<String, String> paramMap = getParamMap(signatureRecord, nlsCreditInfo);
                    final PsdContResult signatureResult = psdContService.signature(signatureRecord.getApplySeq(), getAxqUserId(nlsCreditInfo), tempFileInfo[0], tempFileInfo[1], paramMap);
                    if (signatureResult.isRetFlag()) {
                        signatureRecord.setSiuContNo(signatureResult.getAxqContNo());
                        signatureRecord.setSiuRetMsg("cfca签章成功");
                        //成功走下载流程
                        final PsdContResult psdContResult = psdContService.downSignFile(signatureRecord.getApplySeq(), signatureRecord.getSiuContNo(), tempFileInfo[3]);
                        if (psdContResult.isRetFlag()) {
                            signatureRecord.setSiuSta(1);
                            signatureRecord.setLastUpdateTime(new Date());
                            signatureRecord.setDwnRetMsg("下载文件成功");
                            signatureRecordDAO.updateByPrimaryKey(signatureRecord);
                            insertCfcaSignInfo(psdContResult, nlsCreditInfo, signatureRecord);
                            psdCertUploadService.insert(psdContResult.getFileFullPath());
                            //插入明细表
                            insertImageBizDetail(signatureRecord.getApplySeq(), signatureRecord.getPolFileType(), FilenameUtils.getBaseName(psdContResult.getFileFullPath()), psdContResult.getFileFullPath());
                            insertImageBizInfo(signatureRecord, nlsCreditInfo);
                        } else {
                            signatureRecord.setSiuSta(3);
                            signatureRecord.setLastUpdateTime(new Date());
                            signatureRecord.setDwnRetMsg(psdContResult.getMsg());
                            signatureRecordDAO.updateByPrimaryKey(signatureRecord);
                        }

                    } else {
                        signatureRecord.setSiuSta(2);
                        signatureRecord.setSiuRetMsg(signatureResult.getMsg());
                        signatureRecord.setLastUpdateTime(new Date());
                        signatureRecordDAO.updateByPrimaryKey(signatureRecord);
                    }
                }

            } catch (Exception e) {
                logger.error("处理签章发生异常", e);
                signatureRecord.setErrMsg(e.getMessage());
                signatureRecordDAO.updateByPrimaryKey(signatureRecord);
            }

        }
        return Boolean.TRUE;
    }

    private Map<String, String> getParamMap(SignatureRecord signatureRecord, NlsCreditInfo nlsCreditInfo) {
        HashMap<String, String> paramMap = new HashMap<>();
        if (PsdConstantSet.PSD_FILE_TM_TYPE_03.equals(signatureRecord.getPolFileType())) {
            //脱敏数据
            paramMap.put("cusName", PsdTmUtils.cusNameTm(nlsCreditInfo.getCusName()));
            paramMap.put("certNo", PsdTmUtils.certCodeTm(nlsCreditInfo.getCertCode()));
            paramMap.put("signDate", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")));
            return paramMap;
        } else if (PsdConstantSet.PSD_SX_CONT_TM_TYPE.equals(signatureRecord.getPolFileType())) {
            String siuFillInfo = signatureRecord.getSiuFillInfo();
            Map<String, String> map = JSONObject.parseObject(siuFillInfo, Map.class);
            //脱敏
            //身份证
            map.put("certNoB", PsdTmUtils.certCodeTm(map.get("certNoB")));
            // 电话
            map.put("telB", PsdTmUtils.mobileTm(map.get("telB")));
            // 地址
            map.put("addrB", PsdTmUtils.addrTm(map.get("addrB")));
            //客户名称
            map.put("cusNameB", PsdTmUtils.cusNameTm(map.get("cusNameB")));
            //身份证号
            map.put("identNoB", PsdTmUtils.certCodeTm(map.get("identNoB")));
            return map;
        } else if (PsdConstantSet.PSD_YX_CONT_TM_TYPE.equals(signatureRecord.getPolFileType())) {
            String siuFillInfo = signatureRecord.getSiuFillInfo();
            Map<String, String> map = JSONObject.parseObject(siuFillInfo, Map.class);
            //客户姓名
            map.put("cusName", PsdTmUtils.cusNameTm(map.get("cusName")));
            //证件号码
            map.put("certCode", PsdTmUtils.certCodeTm(map.get("certCode")));
            //客户住址
            map.put("cusAddr", PsdTmUtils.addrTm(map.get("cusAddr")));
            //客户电话
            map.put("cusPhone", PsdTmUtils.mobileTm(map.get("cusPhone")));
            // 放款卡号
            map.put("recvNo", PsdTmUtils.accountTm(map.get("recvNo")));
            return map;
        }
        return paramMap;
    }


    /**
     * 根据处理记录的文件类型获取相应信息
     * [0]合同模板名称
     * [1]合同中文名
     * [2]CfcaSignInfoSeq
     * [3]下载保存使用的文件名
     *
     * @param signatureRecord
     * @return String[]
     */
    private String[] getTempFileInfo(SignatureRecord signatureRecord) {
        if (PsdConstantSet.PSD_FILE_TM_TYPE_03.equals(signatureRecord.getPolFileType())) {
            return new String[]{"sqs.pdf", "个人授权书（个人征信和个人信息）", signatureRecord.getApplySeq() + "_tmsqs", signatureRecord.getApplySeq() + "_tmsqs.pdf"};
        } else if (PsdConstantSet.PSD_SX_CONT_TM_TYPE.equals(signatureRecord.getPolFileType())) {
            return new String[]{"sxcont.pdf", "个人综合授信合同", signatureRecord.getApplySeq() + "_tmsxcont", signatureRecord.getApplySeq() + "_tmsxcont.pdf"};
        } else if (PsdConstantSet.PSD_YX_CONT_TM_TYPE.equals(signatureRecord.getPolFileType())) {
            return new String[]{"dkcont.pdf", "个人借款合同", signatureRecord.getApplySeq() + "_tmdkcont", signatureRecord.getApplySeq() + "_tmdkcont.pdf"};
        }
        return new String[]{"", "", "", ""};
    }

    private String getAxqUserId(NlsCreditInfo nlsCreditInfo) throws Exception {
        PsdContResult openAccountResult = psdContService.openAccount(nlsCreditInfo.getCusName(), nlsCreditInfo.getCertType(), nlsCreditInfo.getCertCode(), nlsCreditInfo.getEmail(), nlsCreditInfo.getIndivMobile(), nlsCreditInfo.getIndivRsdAddr(), nlsCreditInfo.getLmtApplySeq());
        if (openAccountResult.isRetFlag()) {
            return openAccountResult.getAxqUserId();
        } else {
            throw new Exception(openAccountResult.getMsg());
        }
    }

    private void insertCfcaSignInfo(PsdContResult psdContResult, NlsCreditInfo nlsCreditInfo, SignatureRecord signatureRecord) {

        CfcaSignInfoVO cfcaSignInfoVO = new CfcaSignInfoVO();
        //申请流水号
        cfcaSignInfoVO.setApplySeq(getTempFileInfo(signatureRecord)[2]);
        //产品id
        cfcaSignInfoVO.setPrdId(nlsCreditInfo.getPrdId());
        //产品代码
        cfcaSignInfoVO.setPrdCode(nlsCreditInfo.getPrdCode());
        //产品名称
        cfcaSignInfoVO.setPrdName(nlsCreditInfo.getPrdName());
        //合同号
        //cfcaSignInfoVO.setContNo();
        //安心签合同号
        cfcaSignInfoVO.setCfcaContNo(signatureRecord.getSiuContNo());
        //客户号
        cfcaSignInfoVO.setCusId(nlsCreditInfo.getCusId());
        //客户名称
        cfcaSignInfoVO.setCusName(nlsCreditInfo.getCusName());

        cfcaSignInfoVO.setFinaBrId(nlsCreditInfo.getNlsOperOrgid());
        cfcaSignInfoVO.setNlsOperOrgid(nlsCreditInfo.getNlsOperOrgid());
        cfcaSignInfoVO.setNlsOperUserid(nlsCreditInfo.getNlsOperUserid());
        //cfca签署状态 = “未签署”
        cfcaSignInfoVO.setCfcaSignState(ElectronicSignatureEnums.CfcaSignmentStateEnum.SIGN.getEnname());
        cfcaSignInfoVO.setCfcaSignTime(psdContResult.getAxqSignTime());
        cfcaSignInfoService.insertCfcaSignInfo(cfcaSignInfoVO);
    }


    private int[] getHandleNumArr() {
        int[] result = new int[2];
        try {
            SCfgParamVO param = new SCfgParamVO();
            param.setParamKey(PsdConstantSet.MAX_NUM_KEY);
            SCfgParamVO maxNumCfg = sCfgParamService.queryByPk(param);
            if (Objects.isNull(maxNumCfg)) {
                //设置默认值
                result[0] = 50;
            } else {
                result[0] = Integer.parseInt(maxNumCfg.getParamValue());
            }
            param.setParamKey(PsdConstantSet.RETRY_NUM_KEY);
            SCfgParamVO retryNumCfg = sCfgParamService.queryByPk(param);
            if (Objects.isNull(retryNumCfg)) {
                //设置默认值
                result[1] = 3;
            } else {
                result[1] = Integer.parseInt(retryNumCfg.getParamValue());
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return result;
    }


    private void insertImageBizDetail(String applySeq, String imgType, String fileName, String filePath) {
        ImageBizDetailVO imageBizDetail = new ImageBizDetailVO();
        imageBizDetail.setApplySeq(applySeq);
        imageBizDetail.setBizStage("授信阶段");
        imageBizDetail.setFileDesc("普税贷个人授权书");
        imageBizDetail.setFileName(fileName);
        imageBizDetail.setFilePath(filePath);
        imageBizDetail.setImageId(imgType);
        imageBizDetail.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        imageBizDetail.setImageType(imgType);
        imageBizDetailService.insertImageBizDetail(imageBizDetail);
    }


    /**
     * 插入数据到影像业务信息
     *
     * @param nlsCreditInfoVO 目标文件
     */
    private void insertImageBizInfo(SignatureRecord signatureRecord, NlsCreditInfo nlsCreditInfoVO) {
        ImageBizInfoVO param = new ImageBizInfoVO();
        param.setApplySeq(signatureRecord.getApplySeq());
        if (!Objects.isNull(imageBizInfoService.queryByPk(param))) {
            return;
        }
        ImageBizInfoVO imageBizInfo = new ImageBizInfoVO();
        imageBizInfo.setApplySeq(nlsCreditInfoVO.getLmtApplySeq());
        imageBizInfo.setCreateDate(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        imageBizInfo.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        imageBizInfo.setCusId(nlsCreditInfoVO.getCusId());
        imageBizInfo.setCusName(nlsCreditInfoVO.getCusName());
        imageBizInfo.setPrdId(nlsCreditInfoVO.getPrdId());
        imageBizInfo.setPrdCode(nlsCreditInfoVO.getPrdCode());
        imageBizInfo.setPrdName(nlsCreditInfoVO.getPrdName());
        //如下信息先赋空值
        imageBizInfo.setSoltImageAccept("");
        imageBizInfo.setSoltImageCfca("");
        imageBizInfo.setSoltImageThird1("");
        imageBizInfo.setSoltImageThird2("");
        imageBizInfoService.insertOrUpdateImageBizInfoVO(imageBizInfo);
    }

}